package com.xmall.search.define.config;

import com.xmall.msg.queue.ProductModule;
import com.xmall.msg.queue.SearchModule;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class AmqpShareExchangeConfig {

    @Resource
    private RabbitAdmin rabbitAdmin;

    /**
     * 商品更新流向
     * 商品更更新：路由键（product.product.update.key） --> 广播交换机（product.product.update.fanout.exchange）
     *                                             --> 队列（search.product.update.queue）
     */
    @Bean
    public Exchange productUpdateFanoutExchange() {
        FanoutExchange exchange = new FanoutExchange(ProductModule.ProductUpdate.PRODUCT_UPDATE_FANOUT_EXCHANGE);
        rabbitAdmin.declareExchange(exchange);
        return exchange;
    }
    @Bean
    public Queue productUpdateQueue() {
        Queue queue = new Queue(SearchModule.ProductUpdate.PRODUCT_UPDATE_QUEUE, true, false, false);
        rabbitAdmin.declareQueue(queue);
        return queue;
    }
    @Bean
    Binding skuUpdateBinding() {
        Binding binding = BindingBuilder.bind(productUpdateQueue()).to(productUpdateFanoutExchange()).with(SearchModule.ProductUpdate.PRODUCT_UPDATE_ROUTING_KEY).noargs();
        rabbitAdmin.declareBinding(binding);
        return binding;
    }

    /**
     * 商品删除流向
     * 商品删除：路由键（product.product.delete.key） --> 广播交换机（product.product.delete.fanout.exchange）
     *                                            --> 队列（search.product.delete.queue）
     */
    @Bean
    public Exchange productDeleteFanoutExchange() {
        FanoutExchange exchange = new FanoutExchange(ProductModule.ProductDelete.PRODUCT_DELETE_FANOUT_EXCHANGE);
        rabbitAdmin.declareExchange(exchange);
        return exchange;
    }
    @Bean
    public Queue productDeleteQueue() {
        Queue queue = new Queue(SearchModule.ProductDelete.PRODUCT_DELETE_QUEUE, true, false, false);
        rabbitAdmin.declareQueue(queue);
        return queue;
    }
    @Bean
    Binding productDeleteBinding() {
        Binding binding = BindingBuilder.bind(productDeleteQueue()).to(productDeleteFanoutExchange()).with(SearchModule.ProductDelete.PRODUCT_DELETE_ROUTING_KEY).noargs();
        rabbitAdmin.declareBinding(binding);
        return binding;
    }
}
